package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.AuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApAuthor;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    private Configuration configuration;
    @Autowired
    private AuthorMapper authorMapper;
    @Resource(name = "minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Autowired
    private ApArticleMapper apArticleMapper;

    /**
     * 新增静态页面方法
     *
     * @param content
     * @param apArticle
     */
    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {

        try {
            // 1.添加模板对象
            Template template = configuration.getTemplate("article.ftl");
            // 2.获取替换数据
            Map<String, Object> map = new HashMap();
//            map.put("contents", JSONArray.parseArray(content));
            map.put("content", JSON.parseArray(content,Map.class));
            map.put("article", apArticle);
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId", apAuthor.getUserId());
            StringWriter out = new StringWriter();
            template.process(map, out);
            ByteArrayInputStream inputStream = new ByteArrayInputStream(out.toString().getBytes());
            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            apArticle.setStaticUrl(path);
            apArticleMapper.updateById(apArticle);
            log.info("文章详情静态页生成成功 staticUrl=====> {}", path);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}", apArticle.getId(), e.getCause());

        }
        //1.获取文章内容
//        try {
//            //2. 模板
//            Template template = configuration.getTemplate("article.ftl");
//            //3. 数据
//            Map<String, Object> params = new HashMap<>();
//            params.put("content", JSONArray.parseArray(content));// 文章详情
//            params.put("article", apArticle); // 文章信息
//            ApAuthor author = authorMapper.selectById(apArticle.getAuthorId());
//            params.put("authorApUserId", author.getUserId());// 作者 对应的 apUserId
//            StringWriter out = new StringWriter();
//            template.process(params, out);
//            InputStream is = new ByteArrayInputStream(out.toString().getBytes());
//            //4.生成页面把html文件上传到minio中
//            String path = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", is);
//            //5.修改ap_article表，保存static_url字段
//            apArticle.setStaticUrl(path);
//            apArticleMapper.updateById(apArticle);
//            log.info("文章详情静态页生成成功 staticUrl=====> {}", path);
//        } catch (Exception e) {
//            e.printStackTrace();
//            log.error("文章详情静态页生成失败=====>articleId : {}    ========> {}", apArticle.getId(), e.getCause());
//        }
    }
}
